# FastAPI项目 Makefile
.PHONY: build run start stop restart down logs ps help clean tag push login logout check-docker start-docker

# 变量定义
APP_NAME = fastapi-test-app
CONTAINER_NAME = fastapi-test-service
DOCKER_HUB_USER = ayler
VERSION = latest
DOCKER_DESKTOP_PATH = "C:\Program Files\Docker\Docker\Docker Desktop.exe"

# 默认目标
help:
	@echo "FastAPI Docker commands:"
	@echo "make build      - Build Docker image"
	@echo "make run        - Run container (foreground)"
	@echo "make start      - Start container (background)"
	@echo "make stop       - Stop container"
	@echo "make restart    - Restart container"
	@echo "make down       - Stop and remove container"
	@echo "make logs       - View container logs"
	@echo "make ps         - Check container status"
	@echo "make clean      - Clean image and container"
	@echo "make tag        - Tag image"
	@echo "make login      - Login to Docker Hub"
	@echo "make push       - Push image to Docker Hub"
	@echo "make logout     - Logout from Docker Hub"
	@echo "make start-docker - Start Docker Desktop"

# 检查Docker是否运行
check-docker:
	@echo "Checking if Docker is running..."
	@docker info > nul 2>&1 || (echo "Docker is not running, trying to start Docker Desktop..." && $(MAKE) start-docker)

# 启动Docker Desktop
start-docker:
	@echo "Starting Docker Desktop..."
	@start "" $(DOCKER_DESKTOP_PATH)
	@echo "Waiting for Docker Desktop to start (about 30 seconds)..."
	@ping -n 30 127.0.0.1 > nul
	@echo "Trying to reconnect to Docker..."
	@docker info > nul 2>&1 || (echo "Docker is still not running, please start Docker Desktop manually and try again." && exit 1)

# 构建镜像
build: check-docker
	@echo "Building Docker image..."
	docker build -t $(APP_NAME):$(VERSION) -f Dockerfile .

# 运行容器(前台)
run: check-docker
	@echo "Running container (foreground)..."
	docker-compose up fastapi-app

# 启动容器(后台)
start: check-docker
	@echo "Starting container (background)..."
	docker-compose up -d fastapi-app

# 停止容器
stop: check-docker
	@echo "Stopping container..."
	docker-compose stop fastapi-app

# 重启容器
restart: check-docker
	@echo "Restarting container..."
	docker-compose restart fastapi-app

# 停止并删除容器
down: check-docker
	@echo "Stopping and removing container..."
	docker-compose down

# 查看容器日志
logs: check-docker
	@echo "Viewing container logs..."
	docker-compose logs -f fastapi-app

# 查看容器状态
ps: check-docker
	@echo "Checking container status..."
	docker-compose ps

# 清理镜像和容器
clean: check-docker
	@echo "Cleaning container and image..."
	docker-compose down
	docker rmi $(APP_NAME):latest || true

# 给镜像打标签
tag: check-docker
	@echo "Tagging image..."
	docker tag $(APP_NAME):$(VERSION) $(DOCKER_HUB_USER)/$(APP_NAME):$(VERSION)

# 登录Docker Hub
login: check-docker
	@echo "Logging in to Docker Hub..."
	docker login

# 推送镜像到Docker Hub
push: check-docker tag
	@echo "Pushing image to Docker Hub..."
	docker push $(DOCKER_HUB_USER)/$(APP_NAME):$(VERSION)

# 登出Docker Hub
logout: check-docker
	@echo "Logging out from Docker Hub..."
	docker logout 